package s2.action;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;

/**
 * Created by IFT8
 * on 2015/7/18.
 */
public class UploadTest extends ActionSupport implements Serializable {
    /**
     * 格式：
     * 文件： File 文件属性名 必须
     * 文件名： String 文件属性名+FileName
     * 文件MIME类型： String 文件属性名+ContextType
     */
    private File file;
//    private File[] files; //多个用数组
    private String fileFileName;
    private String fileContextType;

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    public String getFileContextType() {
        return fileContextType;
    }

    public void setFileContextType(String fileContextType) {
        this.fileContextType = fileContextType;
    }

    @Override
    public String execute() {
        System.out.println("FileName:  " + fileFileName);
        System.out.println("ContextType:  " + fileContextType);

        ServletContext servletContext = ServletActionContext.getServletContext();
        String realPath = servletContext.getRealPath("/upload");

        try {
            FileUtils.copyFile(file, new File(realPath, fileFileName));
            return SUCCESS;
        } catch (IOException e) {
            e.printStackTrace();
            return ERROR;
        }

//        OutputStream out = null;
//        InputStream in = null;
//        try {
//            out = new FileOutputStream(realPath + '\\' + fileFileName);
//            in = new FileInputStream(file);
//            byte[] buf = new byte[1024];
//            int len;
//            while ((len = in.read(buf)) != -1) {
//                out.write(buf, 0, len);
//            }
//            return SUCCESS;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ERROR;
//        } finally {
//            if (out != null) {
//                try {
//                    out.close();
//                    if (in != null) {
//                        in.close();
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                } finally {
//                    if (in != null) {
//                        try {
//                            in.close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            }
//        }

    }
}
